CONTENTS | INDEX | PREV | NEXT
strtol
NAME
strtol - Convert string to integer
SYNOPSIS
long v = strtol(str, &tail, base);
const char *str;
char *tail;
int base;
FUNCTION
strtol() converts a string into an integer using the specified
base 0-36. If a non-zero base is specified conversion is done
using that base (hex numbers may still be preceeded by '0x' or
'0X'). If 0 is specified for the base then the base is
determined from the first one or two characters of the number
portion of the string:
0 octal
1-9 decimal
0x hex (0x or 0X)
For bases larger than 10, alphabetic characters are used to
represent digits. Either lower case or upper case letters
may be used.
strtol() stores a pointer to the remainder of the string
after the conversion. strtol() ignores any whitespace at
the beginning of the string and also handles an optional
negative sign (which may preceed the numerical portion of
the string).
strtol() returns the converted value as a long, 0 if
it was unable to convert anything, and an undefined result
if the converted value is out of range.
NOTE
strtol() superceeds atoi() and atol().
EXAMPLE
#include <stdio.h>
#include <string.h>
main(ac, av)
char *av[];
{
long v;
char *tail;
if (ac != 3) {
puts("testprg <string> <base>");
puts("testprg 0123abc 0");
puts("testprg 0x1000 0");
puts("testprg 0123abc 16");
exit(1);
}
v = strtol(av[1], &tail, atoi(av[2]));
printf("v = %d, tail = %sn", v, tail);
return(0);
}
1> testprg fffg 16
v = 4095, tail = g
1> testprg -0x100 0
v = -256, tail =
1> testprg 118 8
v = 9, tail = 8
1> testprg 11 0
v = 11, tail =
1> testprg 011xx 0
v = 9, tail = xxx
INPUTS
char *str; pointer to string to convert
char **tail; *tail modified to point to just
after last character converted
int base; base of conversion or 0 for autoselect
RESULTS
long v; converted result, an integer,
or 0 if no conversion could be done.
SEE ALSO
atoi, atol